/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 */
package com.jeesite.modules.interceptor;

import com.jeesite.common.config.Global;
import com.jeesite.common.io.FileUtils;
import com.jeesite.common.service.BaseService;
import com.jeesite.common.utils.SpringUtils;
import com.jeesite.common.web.http.ServletUtils;
import com.jeesite.modules.file.entity.FileUpload;
import com.jeesite.modules.file.service.FileUploadService;
import com.jeesite.modules.utils.MinioUtils;
import org.springframework.util.ClassUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * minio下载拦截器
 *
 * @author ya_jun
 */
public class MinioDownloadInterceptor extends BaseService implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        String preview = ServletUtils.getParameter("preview");
        if (Global.TRUE.equals(preview)) {
            return true;
        } else {
            String requestURI = request.getRequestURI();
            FileUploadService fileUploadService = SpringUtils.getBean(FileUploadService.class);
            FileUpload fileUpload = fileUploadService.get(requestURI.substring(requestURI.lastIndexOf("/") + 1));
            MinioUtils minioUtils = SpringUtils.getBean(MinioUtils.class);
            String fileFullName = ClassUtils.getDefaultClassLoader().getResource("").getPath() + fileUpload.getFileName();
            minioUtils.getRemoteFile(fileUpload.getFileEntity(), fileFullName);
            FileUtils.downFile(new File(fileFullName), request, response, fileUpload.getFileName());
            FileUtils.deleteFile(fileFullName);
            return false;
        }
    }

}
